import 'reflect-metadata';
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { createConnection } from 'typeorm';
import { dbConfig } from './config/database';
import userRoutes from './routes/userRoutes';
import wordRoutes from './routes/wordRoutes';
import categoryRoutes from './routes/categoryRoutes';
import studyPlanRoutes from './routes/studyPlanRoutes';
import studyGoalRoutes from './routes/studyGoalRoutes';
import studyRecordRoutes from './routes/studyRecordRoutes';
import listeningRoutes from './routes/listeningRoutes';
import audioRoutes from './routes/audioRoutes';
import listeningAnalysisRoutes from './routes/listeningAnalysisRoutes';

// 加载环境变量
dotenv.config();

// 创建Express应用
const app = express();

// 中间件
app.use(cors({
  origin: process.env.CORS_ORIGIN || 'http://localhost:8080',
  credentials: true
}));
app.use(express.json());

// 数据库连接
createConnection(dbConfig)
  .then(() => {
    console.log('数据库连接成功');
  })
  .catch((error) => {
    console.error('数据库连接失败:', error);
  });

// 路由
app.get('/', (req, res) => {
  res.json({ message: '英语学习小程序后台API' });
});

app.use('/api/users', userRoutes);
app.use('/api/words', wordRoutes);
app.use('/api/categories', categoryRoutes);
app.use('/api/study-plans', studyPlanRoutes);
app.use('/api/study-goals', studyGoalRoutes);
app.use('/api/study-records', studyRecordRoutes);
app.use('/api/listening', listeningRoutes);
app.use('/api/audio', audioRoutes);
app.use('/api/listening-analysis', listeningAnalysisRoutes);

// 错误处理中间件
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
  console.error(err.stack);
  res.status(500).json({
    message: '服务器错误',
    error: err.message
  });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
}); 